<template>
    <div class="m_right">
        <p></p>
        <div class="mem_tit">商品分类</div>
        <form class="horizontal-form">
            <div class="form-item">
                <label>分类：</label>
                <select v-model="inputType">
                    <option value="">--请选择--</option>
                    <option value="1">一级分类</option>
                    <option value="2">二级分类</option>
                    <option value="3">三级分类</option>
                </select>
                <div class="form-item">
                    <label>名称：</label>
                    <input v-model="inputName">
                </div>

                <div class="form-item">
                    <button @click.prevent="getCategorys(1, 8)">提交</button>
                </div>


            </div>
            <div class="add"><button @click.prevent="addCategory()">添加分类</button></div>

        </form>

        <table>
            <thead>
                <th>序号</th>
                <th>分类名称</th>
                <th>分类级别</th>
                <th>父级分类</th>
                <th>操作</th>
            </thead>
            <tbody>
                <tr v-for="(category, index) in pageInfo.list" :key="category.id">
                    <td>{{ (pageInfo.pageNum - 1) * pageInfo.pageSize + index + 1 }}</td>
                    <td>{{ category.name }}</td>
                    <td>{{ category.type }}级分类</td>
                    <td>{{ getCategoryById(category.parentId) }}</td>
                    <td>
                        <a href="#" @click="delCategory(category.id)">删除</a>&nbsp;&nbsp;
                        <a href="#" @click="update(category.id)">修改</a>
                    </td>
                </tr>
            </tbody>

        </table>
        <!-- 分页条 -->
        <div class="pagination" v-if="pageInfo.pages > 0">
            <button :disabled="pageInfo.pageNum === 1" @click="turn(pageInfo.pageNum - 1)">上一页</button>

            <span v-for="p in showPages" :key="p" :class="{ active: p === pageInfo.pageNum }" @click="turn(p)">{{ p
            }}</span>

            <button :disabled="pageInfo.pageNum === pageInfo.pages" @click="turn(pageInfo.pageNum + 1)">下一页</button>
        </div>
        <!-- 添加 -->
        <div v-show="addShow">
            <p></p>
            <div class="mem_tit">分类添加</div>
            <table>
                <tr>
                    <td style="width: 40%;">商品名称：</td>
                    <td>
                        <input v-model="addCategoryInfo.name" @blur="checkName(addCategoryInfo.name)">
                        <span style="color: red;">{{ errMsg.nameError }}</span>
                    </td>
                </tr>
                <tr>
                    <td style="width: 40%;">请选择分类：</td>
                    <td>
                        <select v-model="addCategoryInfo.type" @change="checkType(addCategoryInfo.type)">
                            <option value="0">--请选择--</option>
                            <option value="1">一级分类</option>
                            <option value="2">二级分类</option>
                            <option value="3">三级分类</option>
                        </select>
                        <span style="color: red;">{{ errMsg.typeError }}</span>

                    </td>
                </tr>
                <tr v-if="addCategoryInfo.type == 2">
                    <td style="width: 40%;">请选择父分类：</td>
                    <td>
                        <select v-model="addCategoryInfo.parentId" @change="checkParentId(addCategoryInfo.parentId)">
                            <option value="">--请选择--</option>
                            <option v-for="category in this.firstCategory" :key="category.id" :value="category.id">
                                {{ category.name }}</option>
                        </select>
                        <span style="color: red;">{{ errMsg.parentIdError }}</span>
                    </td>
                </tr>
                <tr v-if="addCategoryInfo.type == 3">
                    <td style="width: 40%;">请选择父分类：</td>
                    <td>
                        <select v-model="addCategoryInfo.parentId" @change="checkParentId(addCategoryInfo.parentId)">
                            <option value="">--请选择--</option>
                            <option v-for="category in this.secondCategory" :key="category.id" :value="category.id">
                                {{ category.name }}</option>
                        </select>
                        <span style="color: red;">{{ errMsg.parentIdError }}</span>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <button @click="toAdd()">添加</button>&nbsp;&nbsp;
                        <button @click="addShow = false">取消</button>
                    </td>
                </tr>
            </table>
        </div>

        <!-- 修改 -->
        <div v-show="updateShow">
            <p></p>
            <div class="mem_tit">分类修改</div>
            <table>
                <tr>
                    <td style="width: 40%;">所属分类：</td>
                    <td>
                        <select v-model="addCategoryInfo.type" @change="checkType(addCategoryInfo.type)">
                            <option value="0">--请选择--</option>
                            <option value="1">一级分类</option>
                            <option value="2">二级分类</option>
                            <option value="3">三级分类</option>
                        </select>
                        <span style="color: red;">{{ updateErrMsg.typeError }}</span>

                    </td>
                </tr>
                <tr v-if="addCategoryInfo.type != '' && addCategoryInfo.type != '0'">
                    <td style="width: 40%;">所属分类名称：</td>
                    <td>
                        <input v-model="addCategoryInfo.name" @blur="checkName(addCategoryInfo.name)">
                        <span style="color: red;">{{ updateErrMsg.nameError }}</span>
                    </td>
                </tr>
                <tr v-if="addCategoryInfo.type == 2">
                    <td style="width: 40%;">请选择父分类：</td>
                    <td>
                        <select v-model="addCategoryInfo.parentId" @change="checkParentId(addCategoryInfo.parentId)">
                            <option value="">--请选择--</option>
                            <option v-for="category in this.firstCategory" :key="category.id" :value="category.id">
                                {{ updateErrMsg.name }}</option>
                        </select>
                        <span style="color: red;">{{ updateErrMsg.parentIdError }}</span>
                    </td>
                </tr>
                <tr v-if="addCategoryInfo.type == 3">
                    <td style="width: 40%;">请选择父分类：</td>
                    <td>
                        <select v-model="addCategoryInfo.parentId" @change="checkParentId(addCategoryInfo.parentId)">
                            <option value="">--请选择--</option>
                            <option v-for="category in this.secondCategory" :key="category.id" :value="category.id">
                                {{ category.name }}</option>
                        </select>
                        <span style="color: red;">{{ updateErrMsg.parentIdError }}</span>
                    </td>
                </tr>
                <tr>
                    <button @click="toUpdate()">修改</button>&nbsp;&nbsp;
                    <button @click="updateShow = false">取消</button>
                </tr>
            </table>
        </div>

    </div>

</template>

<script>

export default {

    name: 'MemberProductSortRight',
    data() {
        return {
            inputType: '',
            inputName: '',
            allCategory: null,
            pageInfo: null,
            firstCategory: [],
            secondCategory: [],
            thirdCcategory: [],
            categoryWithChild: null,
            treeNode: [],
            addCategoryInfo: {
                id: 0,
                name: '',
                parentId: 0,
                type: 0
            },
            updateCategoryInfo: {
                id: 0,
                name: '',
                parentId: 0,
                type: 0
            },
            errMsg: {
                nameError: '',
                typeError: '',
                parentIdError: ''
            },
            updateErrMsg: {
                nameError: '',
                typeError: '',
                parentIdError: ''
            },
            addShow: false,
            updateShow: false,

            nameFlag: false,
            parentIdFlag: false,
            typeFlag: false

        }
    },
    computed: {
        // 只显示 5 个页码，当前页尽量居中
        showPages() {
            const { pageNum, pages } = this.pageInfo;
            let start = Math.max(pageNum - 2, 1);
            let end = Math.min(start + 4, pages);
            if (end - start < 4) start = Math.max(end - 4, 1);
            const arr = [];
            for (let i = start; i <= end; i++) arr.push(i);
            return arr;
        }
    },
    methods: {
        // 统一翻页方法
        turn(page) {
            if (page < 1 || page > this.pageInfo.pages) return;
            this.getCategorys(page, this.pageInfo.pageSize);
        },
        getCategorys(pageNum, pageSize) {
            this.$axios({
                url: 'selectCategoryByPage',
                method: 'post',
                data: {
                    pageNum: pageNum,
                    pageSize: pageSize,
                    name: this.inputName,
                    type: this.inputType
                },
                headers: {
                    'content-type': 'application/json'
                }
            }).then(rs => {
                if (rs.data.code == 5200 || rs.data.code == '5200') {
                    this.pageInfo = rs.data.pageInfo
                } else {
                    alert('初始化失败！')
                }
            })
        },

        getCategoryById(id) {
            if (id == 0) {
                return '无'
            }
            for (let cate of this.pageInfo.list) {
                if (cate.id == id) {
                    return cate.name
                }
            }

            return '无'
        },
        getPage(opr) {
            let pageNum = 1
            switch (opr) {
                case 'last':
                    pageNum = this.pageInfo.prePage === 0 ? 1 : this.pageInfo.prePage
                    break
                case 'next':
                    pageNum = this.pageInfo.nextPage === 0 ? this.pageInfo.pages : this.pageInfo.nextPage
                    break
                case 'end':
                    pageNum = this.pageInfo.pages
                    break
            }
            this.getCategorys(pageNum, 8)
        },
        addCategory() {
            this.addShow = true
            this.getParentCategorys()
            this.getCategoryWithChild()
            this.convertData()
        },
        toAdd() {
            this.checkName()
            this.checkParentId()
            this.checkType()

            if (this.nameFlag && this.parentIdFlag && this.typeFlag) {
                this.$axios({
                    url: 'addCategory',
                    method: 'post',
                    data: {
                        name: this.addCategoryInfo.name,
                        parentId: this.addCategoryInfo.parentId,
                        type: this.addCategoryInfo.type
                    },
                    headers: {
                        'content-type': 'application/json'
                    }
                }).then(rs => {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        alert('添加成功！')
                        this.getAllCategory()
                        this.nameFlag = false
                        this.typeFlag = false
                        this.parentIdFlag = false
                        this.addShow = false
                    } else {
                        alert('添加失败！')
                    }
                })
            }

        },
        update(id) {
            this.addShow = false
            this.updateShow = true
            this.showCategory(id)
        },
        toUpdate() {
            this.checkType()
            this.checkName()
            this.checkParentId()
            if (this.nameFlag && this.parentIdFlag && this.typeFlag) {
                this.$axios({
                    url: 'updateCategory',
                    method: 'post',
                    data: {
                        id: this.addCategoryInfo.id,
                        name: this.addCategoryInfo.name,
                        type: this.addCategoryInfo.type,
                        parentId: this.addCategoryInfo.parentId
                    },
                    headers: {
                        'content-type': 'application/json'
                    }
                }).then(rs => {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        alert('修改成功！')
                        this.getAllCategory()
                        this.updateShow = false
                        this.nameFlag = false
                        this.typeFlag = false
                        this.parentIdFlag = false
                    } else {
                        alert('修改失败！')
                        this.checkFlag = false
                    }
                })
            }
        },
        showCategory(id) {
            for (let cate of this.pageInfo.list) {
                if (cate.id == id) {
                    this.addCategoryInfo = cate
                    return
                }
            }
        },
        checkType() {
            if (this.addCategoryInfo.type == 1) {
                this.addCategoryInfo.parentId = 0
            }
            if (this.updateCategoryInfo.type == 1) {
                this.updateCategoryInfo.parentId = 0
            }
            if (this.addCategory.type == '' || this.addCategory.type == '0') {
                this.errMsg.typeError = '请选择分类！'
                this.typeFlag = false
            } else {
                this.errMsg.typeError = ''
                this.typeFlag = true
            }
        },
        checkParentId() {
            if (this.addCategory.parentId == '' || this.addCategory.parentId == '0') {
                this.errMsg.parentIdError = '请选择父类！'
                this.parentIdFlag = false
            } else {
                this.errMsg.parentIdError = ''
                this.parentIdFlag = true
            }
        },
        checkName() {

            if (this.addCategoryInfo.name == '') {
                this.errMsg.nameError = '分类名称不能为空！'
                this.nameFlag = false
            } else {
                this.$axios({
                    url: 'checkName',
                    method: 'get',
                    params: { name: this.addCategoryInfo.name, type: this.addCategoryInfo.type }
                }).then(rs => {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        this.errMsg.nameError = ''
                        this.nameFlag = true
                    } else {
                        this.errMsg.nameError = '分类名称重复'
                        this.nameFlag = false
                    }
                })
            }

        },
        getAllCategory() {
            this.$axios({
                url: 'selectAllCategory',
            }).then(rs => {
                if (rs.data.code == 5200 || rs.data.code == '5200') {
                    console.log(rs.data)
                    this.allCategory = rs.data.categoryList
                }
            })
        },
        getParentCategorys() {
            for (let category of this.allCategory) {
                if (category.type == 1) {
                    this.firstCategory.push(category)
                }
                if (category.type == 2) {
                    this.secondCategory.push(category)
                }
                if (category.type == 3) {
                    this.thirdCcategory.push(category)
                }
            }
            console.log(this.thirdCcategory)
        },
        delCategory(id) {
            if (confirm('是否删除？')) {
                this.$axios({
                    url: 'delCategory',
                    method: 'get',
                    params: { id: id }
                }).then(rs => {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        alert('删除成功！')
                        this.getCategorys(1, 8)
                    } else {
                        alert(rs.data.error)
                    }
                })
            }

        },

        getCategoryWithChild() {
            this.$axios({
                url: 'selectRootCategories'
            }).then(rs => {
                if (rs.data.code == 5200 || rs.data.code == '5200') {
                    console.log(rs.data)
                    this.categoryWithChild = rs.data.allCategoryWithChild
                }
            })
        },

        convertData() {
            // 转换函数
            const convertNode = (node) => {
                const newNode = {
                    value: node.id,
                    label: node.name,
                    // 保留其他属性（可选）
                    ...(node.parentId !== undefined && { parentId: node.parentId }),
                    ...(node.type !== undefined && { type: node.type }),
                    ...(node.iconClass !== undefined && { iconClass: node.iconClass }),
                    ...(node.isDelete !== undefined && { isDelete: node.isDelete })
                };

                // 递归处理子节点
                if (node.children && node.children.length > 0) {
                    newNode.children = node.children.map(child => convertNode(child));
                }

                return newNode;
            };

            // 转换整个数据
            this.treeNode = this.originalData.map(node => convertNode(node));

        }
    },

    mounted() {
        this.getCategorys(1, 8)
        this.getAllCategory()

    }

}
</script>
<style scoped>
/* 水平表单 */
.horizontal-form {
    display: flex;
    align-items: center;
    /* 垂直居中 */
    gap: 12px;
    /* 列间距 */
    flex-wrap: wrap;
    /* 小屏自动换行 */
}

.form-item {
    display: flex;
    align-items: center;
    gap: 4px;
    /* label 与 input 间距 */
}

/* 按钮组靠右 */
.buttons {
    margin-left: auto;
}

table {
    width: 90%;
    border-collapse: collapse;
    margin-top: 20px;
    text-align: center;
    border: 1px solid #ddd;
}

th,
td {
    border: 1px solid #ddd;
    /* 内部细线 */
    padding: 6px 10px;
    /* 文字与线之间的空隙 */
}

th:nth-child(1),
td:nth-child(1) {
    width: 60px;
}

/* 序号 */
th:nth-child(2),
td:nth-child(2) {
    width: auto;
}

/* 资讯主题，自适应 */
th:nth-child(3),
td:nth-child(3) {
    width: 150px;
}

/* 发布时间 */
th:nth-child(4),
td:nth-child(4) {
    width: 120px;
}

/* 操作 */
thead>th {
    background: #f5f5f5;
}

tbody tr:hover {
    background: #f5f5f5;
}

/* 分页居中 */
.pagination {
    text-align: center;
    margin-top: 20px;
}

.add>button {
    float: right;
    width: 70px;
    height: 35px;
    border: 1px solid coral;
    background-color: coral;
    color: white;
    margin-right: 25px;
}

/* ---------- 分页条 ---------- */
.pagination {
    width: 85%;
    margin: 20px auto;
    display: flex;
    gap: 8px;
    font-size: 14px;
}

.pagination button {
    border: 1px solid #dcdfe6;
    background: #fff;
    color: #606266;
    padding: 4px 10px;
    border-radius: 3px;
    cursor: pointer;
}

.pagination button:disabled {
    opacity: .4;
    cursor: not-allowed;
}

.pagination span {
    border: 1px solid #dcdfe6;
    padding: 4px 8px;
    cursor: pointer;
}

.pagination span.active {
    background: #ff4e00;
    color: #fff;
    border-color: #ff4e00;
}
</style>